<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j addr-pop-con component-write-logistics-info">
    <!-- 弹窗 -->
    <div class="popup-mask" />
    <div class="fix-transform-blur">
      <div class="popup-box">
        <!-- 新增地址 -->
        <div class="tit">
          <div
            v-if="returnMoneySts !== 3"
            class="text"
          >
            {{ $t('applyReturn.fillLogisticsInformation') }}
          </div>
          <div
            v-if="returnMoneySts === 3"
            class="text"
          >
            {{ $t('applyReturn.modifyLogisticsInformation') }}
          </div>
          <div
            class="close"
            @click="hidePop"
          />
        </div>
        <div class="con">
          <div class="edit logistics-msg">
            <div :class="['item', isLogisticCompanyTip ? 'error-item' : '']">
              <div class="label">
                {{ $t('applyReturn.logisticsCompany') }}：
              </div>
              <div class="select-box">
                <!-- 物流公司 -->
                <el-select
                  v-model="dvyName"
                  :placeholder="$t('applyReturn.select')"
                  class="area"
                  @change="selectCompany"
                >
                  <el-option
                    v-for="company in deliveryList"
                    :key="company.dvyId"
                    style="width: 322px"
                    :label="company.dvyName"
                    :value="company"
                  />
                </el-select>
              </div>
              <div class="error-text-wrap">
                <div
                  v-if="isLogisticCompanyTip"
                  class="error-text"
                >
                  物流公司名称不能为空
                </div>
              </div>
            </div>
            <div :class="['item', (errLnTip || errLnTip1)? 'error':'']">
              <div class="label">
                {{ $t('applyReturn.shipmentNumber') }}：
              </div>
              <div class="text-box">
                <input
                  v-model="LogisticsNumber"
                  type="text"
                  maxlength="30"
                  :placeholder="$t('applyReturn.fillLogisticsBillNumber')"
                  class="input"
                >
                <div
                  v-if="errLnTip"
                  class="error-text"
                >
                  {{ $t('applyReturn.logisticsCannotBeEmpty') }}
                </div>
                <div
                  v-if="errLnTip1"
                  class="error-text"
                >
                  {{ $t('applyReturn.logisticsOrderNoSucced') }}
                </div>
              </div>
            </div>
            <div :class="['item', errLnReMark? 'error':'']">
              <div class="label">
                {{ $t('applyReturn.notes') }}：
              </div>
              <div class="text-box">
                <input
                  v-model="remarks"
                  type="text"
                  maxlength="200"
                  class="input"
                  :placeholder="$t('submitOrder.numberLength200')"
                >
                <div
                  v-if="errLnReMark"
                  class="error-text"
                >
                  {{ $t('inputAllSpace') }}
                </div>
              </div>
            </div>
            <div class="item">
              <div class="label">
                {{ $t('applyReturn.logisticsVouchers') }}：
              </div>
              <div class="text-box">
                <mul-pic-upload
                  v-model="imgs"
                  class="img-upload"
                  :limit="5"
                  :is-logist="true"
                  :file-list="fileList"
                  @img-preview="imgPreview"
                />
                <div class="img-des">
                  （ {{ $t('applyReturn.uploadFiveVouchers') }} ）
                </div>
              </div>
            </div>

            <div class="item">
              <div class="label-btn">
                &nbsp;
              </div>
              <a
                href="javascript:void(0)"
                class="btn-r"
                @click="writeLogisticsMsg"
              >{{ $t('submit') }}</a>
            </div>
          </div>
        </div>
        <!-- /新增地址 -->
      </div>
    </div>
    <!-- /弹窗 -->
    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible">
      <img
        class="dialog-img"
        :src="checkFileUrl(dialogImageUrl)"
        alt
      >
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const props = defineProps({
  refundSn: {
    default: '',
    type: String
  },
  orderNumber: {
    default: '',
    type: [String, Number]
  },
  returnMoneySts: {
    default: null,
    type: Number
  },
  // 退或地址信息
  refundDelivery: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const emit = defineEmits(['toggleAddrPop'])

const router = useRouter()

const dvyName = ref('') // 快递公司名字
let dvyId = 0 // 物流公司id
const LogisticsNumber = ref('') // 物流单号
const remarks = ref('') // 备注
const imgs = ref('')
const fileList = ref([]) // 已上传的凭证图片列表(用于回显)
onMounted(() => {
  loadDeliveryData()
  // 根据物流单号判断回填信息
  if (props.refundDelivery.deyNu) {
    dvyName.value = props.refundDelivery.deyName
    dvyId = props.refundDelivery.deyId
    LogisticsNumber.value = props.refundDelivery.deyNu
    remarks.value = props.refundDelivery.senderRemarks
    imgs.value = props.refundDelivery.imgs
    if (props.refundDelivery.imgs) {
      const temp = props.refundDelivery.imgs.split(',')
      temp.forEach(el => {
        fileList.value.push({ url: checkFileUrl(el) })
      })
    }
  }
})

const dialogVisible = ref(false)
const dialogImageUrl = ref('')
/**
 * 图片预览弹窗
 */
const imgPreview = (url) => {
  dialogImageUrl.value = url
  dialogVisible.value = true
}

const deliveryList = ref([]) // 物流公司
/**
 * 加载物流公司
 */
const loadDeliveryData = () => {
  http.get('/p/delivery/list').then(({ data }) => {
    deliveryList.value = data
  })
}

/**
 * 选择物流公司
 */
const selectCompany = (val) => {
  dvyName.value = val.dvyName
  dvyId = val.dvyId
}

const isLogisticCompanyTip = ref(false)
const errLnTip = ref(false)
const errLnTip1 = ref(false)
const errLnReMark = ref(false)
/**
 * 提交 || 修改物流信息
 */
const writeLogisticsMsg = () => {
  errLnTip.value = false
  errLnTip1.value = false
  errLnReMark.value = false
  isLogisticCompanyTip.value = false
  if (LogisticsNumber.value.length === 0 || /^\s+$/g.test(LogisticsNumber.value)) {
    errLnTip.value = true
    return
  }
  if (!/^[0-9a-zA-Z]+$/.test(LogisticsNumber.value)) {
    errLnTip1.value = true
    return
  }
  if (/^\s+$/g.test(remarks.value)) {
    errLnReMark.value = true
    return
  }

  // 校验 物流公司名称不能为空
  if (!dvyName.value || !dvyId) {
    isLogisticCompanyTip.value = true
    return
  }
  const orderRefundExpressParam = {
    expressId: dvyId,
    expressName: dvyName.value,
    expressNo: LogisticsNumber.value,
    imgs: imgs.value,
    senderRemarks: remarks.value,
    mobile: '',
    refundSn: props.refundSn
  }
  // 当物流单号长度为0时，请求添加物流信息的接口
  if (props.returnMoneySts !== 3) {
    http.post('/p/orderRefund/submitExpress', orderRefundExpressParam).then(() => {
      ElMessage({
        message: $t('applyReturn.fillInSuccessfully') + '！',
        duration: 1000,
        type: 'success'
      })
      router.push({
        path: '/order-detail',
        query: {
          orderNumber: props.orderNumber
        }
      })
    })
  } else if (props.returnMoneySts === 3) {
    // 当物流单号不为空时，请求修改物流信息的接口
    http.put('/p/orderRefund/reSubmitExpress', orderRefundExpressParam)
      .then(() => {
        ElMessage({
          message: $t('applyReturn.modifiedSuccessfully') + '！',
          duration: 1000,
          type: 'success'
        })
        router.push({
          path: '/order-detail',
          query: {
            orderNumber: props.orderNumber
          }
        })
      })
  }
}

/**
 * 隐藏新增地址弹窗
 */
const hidePop = () => {
  emit('toggleAddrPop', false)
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
